import numpy as np
import matplotlib.pyplot as plt
import csv
from scipy.interpolate import interp1d

def stretch_and_interpolate(curve_samples, target_length):
    
    # 初始化一个数组来存储插值填充后的曲线
    interpolated_curves = np.zeros((len(curve_samples), target_length))
    
    # 对每个曲线进行插值填充
    for i, curve in enumerate(curve_samples):
        # 使用插值方法
        f = interp1d(np.linspace(0, 1, len(curve)), curve)
        # 计算插值填充后的曲线
        interpolated_curve = f(np.linspace(0, 1, target_length))
        interpolated_curve_rounded = np.around(interpolated_curve, decimals=1)
        # 将插值填充后的曲线存储到数组中
        interpolated_curves[i] = interpolated_curve_rounded
    
    return interpolated_curves

data = []
with open('data/Output.csv', newline='') as csvfile:
    # 创建一个 CSV 读取器对象
    csv_reader = csv.reader(csvfile)
    # 逐行读取 CSV 文件内容并打印出来
    for row in csv_reader:
        result = ",".join(row)
        data.append(result)

string_list = []
for item in data:
    string_list.append(item)
    
data_X = []
data_y = []    
for string in string_list:
    # 分割字符串并将每个数字字符串转换为整数
    number_list_X = [int(num) for num in string[2:].split(',')]
    number_list_Y = [int(num) for num in string[0]]
    data_X.append(number_list_X)
    data_y.append(number_list_Y)

# 进行拉伸和插值填充

target_length = 300
interpolated_curves = stretch_and_interpolate(data_X, target_length)

fig ,axs = plt.subplots(2,1)
for i,line in enumerate(interpolated_curves):
    if(i == 102):
    # axs[data_y[i][0]].plot(np.linspace(0,300,300),line)
        plt.plot(np.linspace(0,300,300),line)
        plt.xlabel("Number :"+str(i))
        plt.show()
        plt.close()

X_train = np.array(interpolated_curves)
y_train = np.array(data_y)

def z_score_standardization(data):
    # 初始化一个数组用于存储标准化后的数据
    z_score_data = np.zeros_like(data)
    
    # 对每一组数据（每个样本）进行单独的Z-score标准化
    for i in range(data.shape[0]):
        # 计算每组数据的均值和标准差
        mean = np.mean(data[i])
        std = np.std(data[i])
        
        # 对每组数据进行Z-score标准化
        z_score_data[i] = (data[i] - mean) / std
    
    return z_score_data

X_train = z_score_standardization(X_train)
plt.tight_layout()
print(X_train)


# 画原始，拉伸，归一图
# begin
"""idx = 426
import matplotlib.pyplot as plt
lenx = np.linspace(0, len(data_X[idx]), len(data_X[idx]))
lenx_pad = np.linspace(0, len(interpolated_curves[idx]), len(interpolated_curves[idx]))
lenx_nor = np.linspace(0, len(X_train[idx]), len(X_train[idx]))
fig, axs = plt.subplots(3, 1)

# 在第一个子图中绘制原始数据
axs[0].plot(lenx, data_X[idx])
axs[0].set_xlim(0,target_length)
axs[0].set_title("Original data")
# 在第二个子图中绘制插值处理后的数据
axs[1].plot(lenx_pad, interpolated_curves[idx])
axs[1].set_xlim(0,target_length)
axs[1].set_title("Padded data")
# 在第三个子图中绘制标准化处理后的数据
axs[2].plot(lenx_nor, X_train[idx])
axs[2].set_xlim(0,target_length)
axs[2].set_title("Normalized data")
# 显示图表
plt.tight_layout()
plt.show()

# 关闭图表
plt.close()"""

# end


# 分离训练集和测试集
# begin
"""import csv

def copy_and_delete_rows(input_file, output_file):
    # 打开源CSV文件以读取
    with open(input_file, 'r', newline='') as source_file:
        reader = csv.reader(source_file)
        # 创建目标CSV文件并准备写入
        with open(output_file, 'w', newline='') as target_file:
            writer = csv.writer(target_file)
            line_count = 0
            # 逐行读取源文件
            for row in reader:
                line_count += 1
                # 每隔7行写入目标文件
                if line_count % 7 == 0:
                    writer.writerow(row)
    # 删除源文件中被拷贝的行
    with open(input_file, 'r', newline='') as source_file:
        lines = source_file.readlines()
    with open(input_file, 'w', newline='') as source_file:
        for index, line in enumerate(lines):
            if (index + 1) % 16 != 0:
                source_file.write(line)

# 输入文件名和输出文件名
input_filename = 'data/Output.csv'
output_filename = 'data/test.csv'

# 执行函数
copy_and_delete_rows(input_filename, output_filename)"""

# end
